// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'; 
const { DTRO } = require('./dto/index.js')
const { app, BrowserWindow, ipcMain, dialog, session } = require('electron')
// const fs = require('fs')
// const fs = require('node:fs/promises');
const fs = require('node:fs');

const { FileEntity, Config } = require('./entity/index.js')
const path = require('path')
const { spawnSync } = require('node:child_process');

const titleBarOverlayBlur = {
  color: '#323233',
  symbolColor: '#8E8E8E',
  height: 30
}
const titleBarOverlayFocus = {
  color: '#3C3C3C',
  symbolColor: '#CCCCCC',
  height: 30
}
const default_config_path = `${process.cwd()}\\config.json`
const default_session_path = `${process.cwd()}\\session`
const default_backup_path = `${process.cwd()}\\backup`

// TODO后期优化,取消param,rule替代过滤
const filterRule = new Map([
  ['img', new Set(['.jpg', '.png', '.gif', '.bmp', '.jpeg', '.pdf'])],
])

let globe_config = handleReadConfig()


function handleGetFileSync(event, args) {
  const result = new DTRO() //0:异常 1:正常,有返回值 2:正常,无返回值

  // const compute = async (list, threadSize) => {
  //   const size = parseInt(list.length / threadSize)
  //   const threads = []
  //   for (let first = 0, length = size, i = 1; i <= threadSize; i++, first = length, length *= i) {
  //     threads.push(new Thread('./src/thread/task/create_file_entity_worker.js', list.slice(first, length)).run().catch(err => {
  //       console.log('Thread')
  //       console.log(err)
  //     }))
  //   }
  //   const threadResultList = await Promise.all(threads).catch(err => console.log(err))

  //   // TODO 后期优化抛出异常,例:提交后文件被删,导致异常
  //   const reduction = new Set()
  //   const uqSet = new Set()

  //   threadResultList.forEach(element => element.forEach(str => uqSet.add(str)))
  //   uqSet.forEach(str => {
  //     const entity = JSON.parse(str)
  //     if (entity.ext !== '.lnk') reduction.add(entity)
  //   })

  //   return reduction
  // }

  try {
    const list = dialog.showOpenDialogSync(event.sender.getOwnerBrowserWindow(), args)
    if (list === undefined) {
      result.state = 2
    } else {
      const uqSet = new Set()
      const val = new Set()
      for (const dir of list) {
        const stat = fs.statSync(dir)
        if (stat.ext !== '.lnk')
          uqSet.add(
            JSON.stringify(
              new FileEntity(
                dir,
                stat
              )
            )
          )
      }
      uqSet.forEach(str => {
        const entity = JSON.parse(str)
        val.add(entity)
      })

      // result.value = await compute(list, getThreadSize(list.length))
      result.value = val
      result.state = 1
    }
  } catch (e) {
    result.state = 0
    result.value = e
    console.log(e)
  } finally {
    return result
  }
}
function handleGetImageSync(event, args) {
  const result = new DTRO() //0:异常 1:正常,有返回值 2:正常,无返回值
  try {
    const list = dialog.showOpenDialogSync(event.sender.getOwnerBrowserWindow(), args)
    if (list === undefined) {
      result.state = 2
      // 后期优化线程调用
      // 单线程
    } else {
      const uqSet = new Set()
      const val = new Set()

      //list.forEach(dir => uqSet.add(JSON.stringify(new FileEntity(dir, fs.statSync(dir)))))

      for (const dir of list) {
        const stat = fs.statSync(dir)
        if (entity.ext !== '.lnk')
          uqSet.add(
            JSON.stringify(
              new FileEntity(
                dir,
                stat
              )
            )
          )
      }

      const extensions = filterRule.get('img')
      uqSet.forEach(str => {
        const entity = JSON.parse(str)
        if (extensions.has(entity.ext))
          val.add(entity)
      })

      result.value = val
      result.state = 1
    }
  } catch (e) {
    result.state = 0
    result.value = e
    console.log(e)
  } finally {
    return result
  }
}
function handleWindowOpen(win, handlerDetails) {
  return {
    action: 'allow',
    overrideBrowserWindowOptions: {
      parent: win,
      minHeight: 284,
      minWidth: 677,
      show: false,
      title: handlerDetails.frameName,
      modal: true, //后期区分子窗口类型
      titleBarStyle: 'hidden',
      // titleBarOverlay: true,
      titleBarOverlay: {
        color: '#323233',
        // symbolColor: '#74b1be',
        height: 30
      },
      autoHideMenuBar: true,
      // fullscreenable: false,
      webPreferences: {
        preload: path.join(__dirname, 'preload.js') //'my-child-window-preload-script.js'
      }
    }
  }
}
function getResourceLibList() {
  const command = 'Get-PSDrive -PSProvider filesystem | Format-List -property Name,DisplayRoot,Used,Free'
  const ls = spawnSync("powershell.exe", [command]);
  const str0 = ls.stdout.toString()
  const regular0 = /(\r\n)\bName\b\s+: .*(\r\n)\bDisplayRoot\b\s+: .*(\r\n)\bUsed\b\s+: .*(\r\n)\bFree\b\s+: .*(\r\n)/g
  const regular1 = /[A-Za-z0-9]+\s+: .*(\r\n)/g // 行
  const regular2 = /[A-Za-z]+\s+:/g //属性名
  const regular3 = /[a-zA-Z0-9]+/g //值
  const regular4 = /: .*(\r\n)/g //属性值
  const regular5 = /:\s+/g
  const regular6 = /(\r\n)/g
  const libList = []

  str0.match(regular0).forEach(str1 => {
    const lib = {}
    str1.match(regular1).forEach(str2 => {
      lib[str2.match(regular2)[0].match(regular3)[0]] = str2.match(regular4)[0].replace(regular5, '').replace(regular6, '')
    })
    libList.push(lib)
  })
  return libList
}
function handleCreateNewConfig() {
  const config = new Config('admin', '123456', default_backup_path, default_session_path)
  try {
    return fs.writeFileSync(default_config_path, JSON.stringify(config), { encoding: 'utf8' })
  } catch (e) {
    console.log(e)
  }
}
function handleReadConfig() {
  try {
    const jsonStr = fs.readFileSync(default_config_path, { encoding: 'utf8' })
    const config = JSON.parse(jsonStr)
    return config
  } catch (e) {
    if (e.code === 'ENOENT') {
      handleCreateNewConfig()
      return handleReadConfig()
    }
  }
}

function handlePutConfig(event, config) {
  try {
    fs.writeFileSync(default_config_path, JSON.stringify(config), { encoding: 'utf8' })
    globe_config = config
    return new DTRO(2)
  } catch (e) {
    console.log(e)
    return new DTRO(0, e)
  }
}

function handlePutAccount(event, account) {
  try {
    globe_config.username = account.username
    globe_config.password = account.password
    fs.writeFileSync(default_config_path, JSON.stringify(globe_config), { encoding: 'utf8' })

    return new DTRO(2)
  } catch (e) {
    console.log(e)
    return new DTRO(0, e)
  }
}

function handleStoreExport(event, storeCopy) {
  try {
    fs.writeFileSync(`${globe_config.backup_path}\\${storeCopy.timeStamp}.json`, JSON.stringify(storeCopy), { encoding: 'utf8' })
    return new DTRO(1)
  } catch (e) {
    console.log(e)
    return new DTRO(0, e)
  }
}
function handleStoreExportAs(event, args) {
  const result = new DTRO() //0:异常 1:正常,有返回值 2:正常,无返回值
  try {
    const savePath = dialog.showSaveDialogSync(event.sender.getOwnerBrowserWindow(), args[1])
    if (savePath === undefined)
      result.state = 2
    else {
      result.state = 1
      fs.writeFileSync(`${savePath}.json`, JSON.stringify(args[0]), { encoding: 'utf8' })
    }
  } catch (e) {
    result.state = 0
    result.value = e
    console.log(e)
  } finally {
    return result
  }
}
function handleStoreCopyGet(event, args) {
  const result = new DTRO() //0:异常 1:正常,有返回值 2:正常,无返回值
  try {
    args.defaultPath = globe_config.backup_path
    const storeCopy = dialog.showOpenDialogSync(event.sender.getOwnerBrowserWindow(), args)
    if (storeCopy) {
      result.value = fs.readFileSync(storeCopy[0], { encoding: 'utf8' })
      result.state = 1
    } else
      result.state = 2
  } catch (e) {
    result.state = 0
    result.value = e
    console.log(e)
  } finally {
    return result
  }
}

function createMainWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    minHeight: 284,
    minWidth: 677,
    title: 'my-lib',
    show: false,
    // frame: false,
    //自定义顶部标题栏,按钮宽度未知
    titleBarStyle: 'hidden',
    // titleBarOverlay: true,
    titleBarOverlay: {
      color: '#323233',
      // symbolColor: '#74b1be',
      height: 30
    },
    kiosk: false, //全屏
    // autoHideMenuBar: true,
    webPreferences: {
      // __dirname 字符串指向当前正在执行脚本的路径 (在本例中，它指向你的项目的根文件夹)
      // path.join API 将多个路径联结在一起，创建一个跨平台的路径字符串
      preload: path.join(__dirname, 'preload.js'),
      session: session.fromPath(globe_config.session_path, { cache: true })
    }
  })
  win.loadFile('src/views/my-lib-main.html')
  return win
}

// 全局启用沙盒
app.enableSandbox()
// 监听Ready事件
app.whenReady().then(() => {
  ipcMain.handle('dialog:getFile', handleGetFileSync)
  ipcMain.handle('dialog:getImage', handleGetImageSync)
  ipcMain.handle('system:getLibList', getResourceLibList)
  ipcMain.handle('config:get', () => globe_config)
  ipcMain.handle('config:put', handlePutConfig)
  ipcMain.handle('config:putAccount', handlePutAccount)
  ipcMain.handle('store:export', handleStoreExport)
  ipcMain.handle('store:exportAs', handleStoreExportAs)
  ipcMain.handle('store:getCopy', handleStoreCopyGet)


  const mainWindow = createMainWindow()
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })
})

app.on('browser-window-created', (event, window) => {
  window.webContents.setWindowOpenHandler(handlerDetails => handleWindowOpen(window, handlerDetails))
  window.once('ready-to-show', () => {
    window.show()
  })
})
// 监听'window-all-closed' 事件
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})
app.on('browser-window-blur', (event, window) => {
  window.setTitleBarOverlay(titleBarOverlayBlur)
  window.webContents.send('window:blur', 0)
})
app.on('browser-window-focus', (event, window) => {
  window.setTitleBarOverlay(titleBarOverlayFocus)
  window.webContents.send('window:focus', 1)
})


